package com.csx.framework.springboot.sample.data.transaction;

import com.csx.framework.springboot.sample.data.transaction.entity.User;
import com.csx.framework.springboot.sample.data.transaction.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.List;

/**
 *
 * @author cuisongxu
 * @date 2024/12/21 周六 13:06
 */

@Component
public class TransactionManagerSample {

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private UserService userService;

    /**
     * 使用 PlatformTransactionManager 进行事务操作
     */
    public void testTransactionManager() {

        TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            // 业务代码
            userService.insertUser(997L, "张", "三", 18, "深圳");
            // 模拟插入失败
            userService.insertUserFail(998L, "张2", "2", 18, "深圳");
            List<User> allUsers = userService.getAllUsers();
            System.out.println(allUsers);
            // 提交事务
            transactionManager.commit(transactionStatus);
        }catch (Exception e) {

            // 回滚事务
            transactionManager.rollback(transactionStatus);
        }
    }
}
